package com.xiaozhen.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.security.controller.BaseController;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.system.SysTenant;
import com.xiaozhen.system.service.SysTenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/27 15:23
 * @description:
 */
@Api(tags = "系统租户接口")
@RestController
@RequestMapping("/sysTenant")
public class SysTenantController extends BaseController {

    @Autowired
    private SysTenantService sysTenantService;

    @ApiOperation("获取租户列表")
    @GetMapping("/list")
    public AjaxResult list() {
        Page<SysTenant> page = startPage();
        Page<SysTenant> list = sysTenantService.selectSysTenantList(page);
        return getDataTable(list);
    }


    @ApiOperation("添加租户信息")
    @PostMapping("/addSysTenant")
    public AjaxResult addSysTenant(@Validated @RequestBody SysTenant sysTenant) {
        if (!sysTenantService.checkTenantNameUnique(sysTenant)) {
            return AjaxResult.error("新增租户'" + sysTenant.getTenantName() + "'失败，租户名称已存在");
        }
        sysTenant.setCreateBy(getCurrentUserId());
        sysTenant.setCreateTime(LocalDateTime.now());
        return toAjax(sysTenantService.insertSysTenant(sysTenant));
    }

    @ApiOperation("修改租户信息")
    @PutMapping("/updateSysTenant")
    public AjaxResult updateSysTenant(@Validated @RequestBody SysTenant sysTenant) {
        if (!sysTenantService.checkTenantNameUnique(sysTenant)) {
            return AjaxResult.error("修改租户'" + sysTenant.getTenantName() + "'失败，租户名称已存在");
        }
        sysTenant.setUpdateBy(getCurrentUserId());
        sysTenant.setUpdateTime(LocalDateTime.now());
        if (sysTenantService.updateSysTenant(sysTenant) > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改租户'" + sysTenant.getTenantName() + "'失败，请联系管理员");
    }

    @ApiOperation("删除租户信息")
    @DeleteMapping("/{tenantIds}")
    public AjaxResult remove(@PathVariable Long[] tenantIds) {
        return toAjax(sysTenantService.deleteTenantByIds(tenantIds));
    }

}
